package cn.com.yto56.cainiao.exponent.front.service.impl;

import cn.com.yto56.basic.framework.core.util.DateUtil;
import cn.com.yto56.basic.framework.plugin.elasticsearch.ElasticSearchStarter;
import cn.com.yto56.cainiao.exponent.common.QueryDSL;
import cn.com.yto56.cainiao.exponent.front.service.CommonService;
import cn.com.yto56.cainiao.exponent.front.service.FrontHandleService;
import com.alibaba.fastjson.JSONPath;
import org.frameworkset.elasticsearch.entity.MapRestResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

@Service("frontHandleServiceImpl")
public class FrontHandleServiceImpl implements FrontHandleService {
    private static final String FRONT_FMT = "yyyy-MM-dd HH:mm:ss";
    private static final String FRONT_LOG_PATH = "yto-log-front-*/0/_search";
    private static final int MAX_DAY = -15;

    @Autowired
    private ElasticSearchStarter starter;

    @Override
    public MapRestResponse query(String path, String entity) {
        return CommonService.search(starter.getRestClient(), path, entity);
    }

    @Override
    public String queryInbound(String mailNo) {
        Map<String, String> map = getQueryMapper(mailNo);
        map.put("opCode", "751");
        String entity = CommonService.compileString(QueryDSL.FRONT_LOG_TEMPLATE, map);
        MapRestResponse response = query(FRONT_LOG_PATH, entity);
        Object sendMessage = JSONPath.eval(response, "$.searchHits.hits[0].source.sendMessage");
        if (sendMessage != null) {
            return String.valueOf(JSONPath.extract(String.valueOf(sendMessage), "$.operEmpPhone"));
        }
        return null;
    }

    @Override
    public Date queryCanvassTime(String mailNo) {
        Map<String, String> map = getQueryMapper(mailNo);
        map.put("opCode", "310");
        String entity = CommonService.compileString(QueryDSL.FRONT_LOG_TEMPLATE, map);
        MapRestResponse response = query(FRONT_LOG_PATH, entity);
        Object sendMessage = JSONPath.eval(response, "$.searchHits.hits[0].source.sendMessage");
        if (sendMessage != null) {
            Object operTime = JSONPath.extract(String.valueOf(sendMessage), "$.operTime");
            if (operTime != null) {
                return DateUtil.toDate(String.valueOf(operTime), FRONT_FMT);
            }
        }
        return null;
    }

    private Map<String, String> getQueryMapper(String mailNo) {
        Map<String, String> map = CommonService.getSearchTime(new Date(), MAX_DAY);
        map.put("mailNo", mailNo);
        return map;

    }
}
